#include <ADC.h>

void ADC_power(bool STATE)
{
    // Bit7 ADCEN 1开 0关
    if (STATE)
    {
        ADCCON |= 0x80;
    }
    else
    {
        ADCCON &= 0x7F;
    }
}

void ADC_setAINs(uint16_t AINx, bool STATE)
{
    uint8_t temp0;
    uint8_t temp1;
    // ADC 设置寄存器 ADCCFG0~1
    temp0 = (uint8_t)(AINx & 0xFF);
    temp1 = (uint8_t)(AINx >> 8);
    if (STATE)
    {
        ADCCFG0 |= temp0;
        ADCCFG1 |= temp1;
    }
    else
    {
        ADCCFG0 &= ~temp0;
        ADCCFG1 &= ~temp1;
    }
}

void ADC_setPeriod(uint8_t PERIOD)
{
    ADCCFG2 = PERIOD;
}

void ADC_setVref(uint8_t VREFS)
{
    OPINX = 0xC2;
    OPREG &= 0x3F;
    OPREG |= VREFS << 6;
}

/**
 * @brief ADC初始化
 * 
 * @param AINx ADC输入口
 * @param PERIOD ADC扫描周期
 * @param VREFS ADC参考电压
 */
void ADC_init(uint16_t AINx, uint8_t PERIOD, uint8_t VREFS)
{
    ADC_setAINs(AINx, true);
    ADC_setPeriod(PERIOD);
    ADC_setVref(VREFS);
}

void ADC_select(uint8_t ADCx)
{
    ADCCON &= 0xE0;
    ADCCON |= ADCx;
}

void ADC_begin()
{
    SET_BIT(ADCCON, BIT(6));
}

/**
 * @brief 
 * 
 * @param ADCx 
 * @return uint16_t 
 */
uint16_t ADC_getVoltageSync(uint8_t ADCx)
{
    uint16_t temp = 0;
    // 打开电源
    ADC_power(true);
    // 选中通道
    ADC_select(ADCx);
    // 启动ADCS
    ADC_begin();
    while(!READ_BIT(ADCCON, BIT(5)))
        ;
    CLEAR_BIT(ADCCON, BIT(5));
    temp = ((ADCVH << 4) | (ADCVL >> 4));
    return temp;
}
